/**
 * @author Austin Andrews (Templarian)
 * @authorurl http://templarian.com
 * @framework DD Framework
 * @licence MIT License
 * @licenceurl http://ddframework.googlecode.com/svn/trunk/license.txt
 * @overview Dynamically load styles and allocate stylesheets.
 */
dd.dss({
    /**
     * Comment Here
     */
    addStyle:function(selector, style, layer)
    {
        layer = layer || style;
        //try
        //{
            for(i = 0; i < dd.dss[layer].cssRules.length; i++)
            {
                if(dd.dss[layer].cssRules[i].selectorText.toLowerCase() == selector.toLowerCase())
                {
                    dd.dss[layer].cssRules[i].style.cssText = style;
                    return;
                }
            }
            dd.dss[layer].insertRule(layer == style ? selector : selector + "{" + style + "}", dd.dss[layer].cssRules.length);
        //}
        //catch(e)
        //{
        //    if(console)
        //    console.log("Error: Selector '" + selector + "' with style '" + style + "' failed.");
        //}
    },
    /**
     * Comment Here
     */
    createLayer:function(name, media)
    {
        media = media || "screen";
        dd(dd.head).addElement("style", {"type":"text/css", "media":media});
        dd.dss[name] = document.styleSheets[document.styleSheets.length - 1];
    },
    /**
     * Comment Here
     */
    clear:function(name)
    {
        while(dd.dss[name].cssRules.length)
        {
            dd.dss[name].deleteRule(dd.dss[name].cssRules.length - 1);
        }
    },
    _selector:{"hover":""},
    _cache:{},
    /**
     * Comment Here
     */
    func:function(o, s)
    {
        s = s || {};
        o.overwrite = o.overwrite || false;
        if(dd.dss._cache.hasOwnProperty(o.url))
        {
            if(o.overwrite)
            {
                dd.dss.clear(o.layer);
            }
            for(var i = 0; i < dd.dss._cache[o.url].length; i++)
            {
                dd.dss.addStyle(dd.dss._cache[o.url][i], o.layer);
            }
            if(o.success)
            {
                o.success.call(s);
            }
            return true;
        }
        dd.http({
            url:o.url,
            success:function()
            {
                if(this.overwrite)
                {
                    dd.dss.clear(this.layer);
                }
                var t = this.text.split("");
                var indent = 0;
                var select = [];
                var temp = "";
                var style = [];
                var line = 1;
                var ignore = false;
                var property = "";
                var joinType = ">";
                for(var i = 0; i < t.length; i++)
                {
                    if(t[i] != "\n" && ignore)
                    {
                        continue;
                    }
                    switch(t[i])
                    {
                        case "/": // Comments
                            if(t[i + 1] == "/")
                            {
                                ignore = true;
                                i++;
                            }
                            else
                            {
                                temp += t[i];
                            }
                            break;
                        case "&": // Handle &. &: &_
                            if(t[i + 1] == "." ||
                               t[i + 1] == ":" ||
                               t[i + 1] == "_")
                            {
                                joinType = t[i + 1];
                                temp += t[i] + t[i + 1];
                                i++;
                            }
                            else
                            {
                                temp += t[i];
                            }
                            break;
                        case "{":
                            indent++;
                            if(select.length > 0 && style.length > 0)
                            {
                                var v = select.slice(0);
                                for(var j = 1; j < v.length; j++)
                                {
                                    if(/&/.test(v[j]))
                                    {
                                        v[j - 1] = v.splice(j, 1)[0].replace("&", v[j - 1]);
                                        j--;
                                    }
                                }
                                dd.dss.addStyle(
                                    v.join(" > "),
                                    style.join(";") + ";",
                                    this.layer
                                );
                            }
                            if(/\s*/.test(temp))
                            {
                                select.push(dd.trim(temp));
                                style = [];
                            }
                            temp = "";
                            break;
                        case "}":
                            indent--;
                            if(style.length > 0)
                            {
                                var v = select.slice(0);
                                for(var j = 1; j < v.length; j++)
                                {
                                    if(/&/.test(v[j]))
                                    {
                                        v[j - 1] = v.splice(j, 1)[0].replace("&", v[j - 1]);
                                        j--;
                                    }
                                }
                                dd.dss.addStyle(v.join(" > "), style.join(";") + ";", this.layer);
                                style = [];
                            }
                            select.pop();
                            temp = "";
                            break;
                        case ":":
                            if(t[i + 1] == ":" || t[i - 1] == ":")
                            {
                                temp += t[i];
                            }
                            else
                            {
                                property = dd.trim(temp);
                                temp = "";
                            }
                            break;
                        case ";":
                            var v = dd.trim(temp);
                            switch(property)
                            {
                                case "user-select":
                                case "box-shadow":
                                case "border-top-colors":
                                case "border-right-colors":
                                case "border-bottom-colors":
                                case "border-left-colors":
                                case "opacity":
                                case "box-orient":
                                case "box-pack":
                                case "box-align":
                                case "box-flex":
                                    style.push("-moz-" + property + ":" + v);
                                    style.push("-webkit-" + property + ":" + v);
                                    style.push("-o-" + property + ":" + v);
                                    break;
                                case "display":
                                    if(v == "box")
                                    {
                                        style.push(property + ":-moz-" + v);
                                        style.push(property + ":-webkit-" + v);
                                    }
                                    break;
                            }
                            style.push(property + ":" + v);
                            property = "";
                            temp = "";
                            break;
                        case "\n":
                            if(t[i - 1] == ",")
                            {
                                temp = "";
                            }
                            ignore = false;
                            line++;
                            break;
                        case "\r":
                            // Ignore
                            break;
                        default:
                            temp += t[i];
                    }
                }
                if(indent == 0)
                {
                    // Cache Results (added lines for chrome bug)
                    dd.dss._cache[this.file] = [];
                    if(dd.dss[this.layer] && dd.dss[this.layer].cssRules && dd.dss[this.layer].cssRules.length)
                    {
                        for(var i = 0; i < dd.dss[this.layer].cssRules.length; i++)
                        {
                            dd.dss._cache[this.file][i] = dd.dss[this.layer].cssRules[i].cssText;
                        }
                    }
                    // Success
                    if(this.success)
                    {
                        this.success.call(this.s);
                    }
                }
                else
                {
                    if(this.failure)
                    {
                        this.failure.call({
                            errorCode:1,
                            error:"Unmatched braces on line " + line + ".",
                            line:line
                        });
                    }
                }
            },
            failure:function()
            {
                if(this.failure)
                {
                    this.failure.call({
                        errorCode:0,
                        error:"Failed to load.",
                        line:-1
                    });
                }
            }
        }, {overwrite:o.overwrite, layer:o.layer, s:s, success:o.success, failure:o.failure});
        return true;
    }
});